#!/usr/local/bin/php

<?php
  require_once('daemons.conf.php');
  require_once('lib/ses.php');
  require_once("lib/db.broker.php");
  require_once("lib/create-daemon.php");

  function get_bounce_action($file_str) {
    
    if (preg_match('/complaints@email-abuse.amazonses.com/', $file_str)) {
      return array('action' => 'deactivate', 'reason' => 'complaint');
    }
        
    if (preg_match('/Diagnostic-Code(.*)DNS\sHard\sError(.*)/', $file_str)) {
      return array('action' => 'deactivate', 'reason' => 'dns-hard');
    }  

    if (preg_match('/Diagnostic-Code(.*)DNS\sSoft\sError(.*)/', $file_str)) {
      return array('action' => 'deactivate', 'reason' => 'dns-soft');
    }

    return array('action' => 'bounce', 'reason' => 'unidentify');

  } // get_bounce_action()


  $db = New broker;

  while(true) {

    if ($signal_code) {
      exit;
    }

    // get folder contents
    $bounces = scandir(BOUNCES_FOLDER);

    foreach ($bounces as $bounce) {

      if ($signal_code) {
        exit;
      }

      // discard directories and . and ..
      if (($bounce != '.') and ($bounce != '..') and ( ! is_dir(BOUNCES_FOLDER . $bounce))) {
        
        // file to string
        $file_str = file_get_contents(BOUNCES_FOLDER . $bounce);
        
        // get AWS message-id line from file string
        if (preg_match('/Message-ID:\s<.*@/', $file_str, $aws_message_id)) {

          // remove extra chars to get the AWS message-id
          $awsmessage_id = str_replace('@', '', $aws_message_id[0]);
          $awsmessage_id = str_replace('Message-ID: <', '', $awsmessage_id);
          
          $bounce_action = get_bounce_action($file_str);

          if ($bounce_action['action'] === 'deactivate') {
            
            // if not complaint, mark send as bounced
            if ($bounce_action['reason'] != 'complaint') {
              $bounce_update = "
                UPDATE 
                  sends 
                SET 
                  bounced = NOW() 
                WHERE 
                  awsmessageid = '{$awsmessage_id}'  
              ";

              $db->update($bounce_update);
            }

            // get recipient id
            $query ="
              SELECT 
                recipient_id 
              FROM 
                sends
              WHERE 
                awsmessageid = '{$awsmessage_id}'
            ";

            $recipient_query = $db->query($query);

            if (count($recipient_query) > 0) {

              // update off status of recipient
              $off_update = "
                UPDATE 
                  recipients 
                SET 
                  offdate   = NOW(),
                  offreason = '{$bounce_action['reason']}'
                WHERE 
                  recipients.id = {$recipient_query[0]['recipient_id']}
              ";

              //error_log("{$off_update}\r\n", 3, LOG_FILE);
              $db->update($off_update);
            }

          } // if ($bounce_action['action'] === 'deactivate')
          else {

            // mark send as bounced
            $update_bounce = "
              UPDATE 
                sends 
              SET 
                bounced = NOW() 
              WHERE 
                awsmessageid = '{$awsmessage_id}'  
            ";

            //error_log("{$update_bounce}\r\n", 3, LOG_FILE);
            $db->update($update_bounce);

          } // else de if ($bounce_action['action'] === 'deactivate')
        } // if (preg_match ...

        //error_log("unlink\r\n", 3, LOG_FILE);
        unlink(BOUNCES_FOLDER . $bounce);

      } // if discard directories and . and ..
    } // foreach

    if ($signal_code) {
      exit;
    }
    
    usleep(30000000); // dejamos descansar 30seg el procesador :)
  } // while(true)
